package atom.core0.http.ssl;

import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

public class SSLSocketFactoryUtil {
	
	public static SSLSocketFactory getSSLSocketFactory(TrustManager[] tm,String[] exludedCipherSuites ) throws Exception
	{
		// 从上述SSLContext对象中得到SSLSocketFactory对象
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, tm, null);
        SSLSocketFactory ssf = sslcontext.getSocketFactory();
        
        //如果去全部算法，则直接返回
        if(exludedCipherSuites==null)
        	return ssf;
        //获取算法
        SSLParameters params = sslcontext.getSupportedSSLParameters();
        List<String> enabledCiphers = new ArrayList<String>();
        for (String cipher : params.getCipherSuites()) {
            boolean exclude = false;
            if (exludedCipherSuites != null) {
                for (int i=0; i<exludedCipherSuites.length && !exclude; i++) {
                    exclude = cipher.indexOf(exludedCipherSuites[i]) >= 0;
                }
            }
            if (!exclude) {
                enabledCiphers.add(cipher);
            }
        }
        String[] cArray = new String[enabledCiphers.size()];
        enabledCiphers.toArray(cArray);

        // Tell the URLConnection to use a SocketFactory from our SSLContext
        
        ssf = new DOSSLSocketFactory(ssf, cArray);
        return ssf;
        
        
	}
	public static SSLSocketFactory getJDK7SSLSocketFactory(TrustManager[] tm) throws Exception
	{
		String[] exludedCipherSuites = {"_DHE_","_DH_"};
		return SSLSocketFactoryUtil.getSSLSocketFactory(tm, exludedCipherSuites);
	}
}
